<template>
  <el-container>
    <el-header>
      <TopBar />
    </el-header>
    <el-main class="el-main">
      <div class="content">
        <!-- 社团基本信息 -->
        <div class="club-header">
          <div class="img-details">
            <img
              :src="clubData.clubimg || defaultImg"
              alt=""
              class="clubimg-details round-img"
            >
          </div>
          <div class="club-info">
            <div class="clubname-details">{{ clubData.clubname }}</div>
            <div class="club-description">{{ clubData.description || '这个社团暂时没有简介' }}</div>
            <div class="club-stats">
              <div class="stat-item">
                <span class="stat-value">{{ clubData.memberCount || 0 }}</span>
                <span class="stat-label">成员</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ clubData.posts?.length || 0 }}</span>
                <span class="stat-label">帖子</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ clubData.active?.length || 0 }}</span>
                <span class="stat-label">活动</span>
              </div>
            </div>
            <div class="club-actions">
              <el-button v-if="!isMember" type="primary" round @click="openJoinDialog">加入社团</el-button>
              <!-- 社团管理入口，仅对社团管理员显示 -->
              <el-button
                v-if="isClubAdmin"
                type="warning"
                round
                @click="goToClubManage()"
              >
                社团管理
              </el-button>
            </div>
          </div>
        </div>

        <!-- 内容导航 -->
        <div class="club-nav">
          <div
            v-for="tab in tabs"
            :key="tab.key"
            class="nav-item"
            :class="{ active: activeTab === tab.key }"
            @click="activeTab = tab.key"
          >
            {{ tab.label }}
          </div>
        </div>

        <!-- 社团活动展示 -->
        <div v-if="activeTab === 'activities'" class="club-activities">
          <h2 class="section-title">社团活动</h2>
          <div v-if="!clubData.active || clubData.active.length === 0" class="no-data">暂无活动安排</div>
          <div v-else class="activities-grid">
            <el-card
              v-for="activity in sortedActivities"
              :key="activity.activeid || activity._id"
              class="activity-card"
              :class="getActivityStatusClass(activity)"
            >
              <div class="activity-status">
                <el-tag :type="getActivityStatusType(activity)">{{ getActivityStatusText(activity) }}</el-tag>
              </div>
              <h4>{{ activity.activename }}</h4>
              <div class="activity-info">
                <p><i class="el-icon-time"></i> {{ formatDateTime(new Date(activity.activetime)) }} - {{ formatDateTime(new Date(activity.endTime)) }}</p>
                <p><i class="el-icon-location"></i> 活动地点：{{ activity.activeadd }}</p>
                <p v-if="activity.maxParticipants">
                  <i class="el-icon-user"></i> 人数上限：{{ activity.maxParticipants }}
                </p>
              </div>
              <div class="activity-description" v-if="activity.description">
                <p>{{ truncateText(activity.description, 80) }}</p>
              </div>
              <div class="activity-action">
                <el-button
                  v-if="!hasUserRegistered(activity) && canRegister(activity)"
                  size="small"
                  type="primary"
                  round
                  @click="openRegisterDialog(activity)"
                >报名参加</el-button>
                <el-button
                  v-if="hasUserRegistered(activity) && canRegister(activity)"
                  size="small"
                  type="danger"
                  round
                  @click="cancelRegistration(activity)"
                >取消报名</el-button>
                <el-button
                  v-if="isActivityOngoing(activity)"
                  size="small"
                  type="info"
                  round
                  disabled
                >进行中</el-button>
                <el-button
                  v-if="isActivityCompleted(activity)"
                  size="small"
                  type="danger"
                  round
                  disabled
                >已结束</el-button>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 社团成员展示 -->
        <div v-if="activeTab === 'members'" class="club-members">
          <h2 class="section-title">社团成员</h2>
          <div class="member-filter">
            <el-radio-group v-model="memberFilter" size="small">
              <el-radio-button label="all">全部成员</el-radio-button>
              <el-radio-button label="admin">管理团队</el-radio-button>
            </el-radio-group>
          </div>
          <div v-if="!filteredMembers.length" class="no-data">暂无成员信息</div>
          <div v-else class="members-grid">
            <el-card v-for="member in filteredMembers" :key="member.id" class="member-card">
              <div class="member-avatar">
                <img :src="member.avatar || defaultImg" alt="" class="round-img">
              </div>
              <div class="member-info">
                <div class="member-name">{{ member.name }}</div>
                <div class="member-role">{{ member.role }}</div>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 社团帖子 -->
        <div v-if="activeTab === 'posts'" class="club-posts">
          <h2 class="section-title">社团帖子</h2>
          <div v-if="!clubData.posts || clubData.posts.length === 0" class="no-data">暂无帖子</div>
          <div v-else class="posts-wrapper">
            <PostWaterfall
              ref="postWaterfall"
              :posts="clubData.posts"
              :columns="0"
              @post-click="openPostDetail"
            />
          </div>
        </div>
      </div>
      <PostDetailModal v-if="selectedPost" :post="selectedPost" @close="selectedPost = null" />

      <!-- 加入社团申请表单弹窗 -->
      <el-dialog
        title="加入社团申请"
        v-model="showJoinDialog"
        width="50%"
      >
        <el-form :model="joinForm" :rules="joinFormRules" ref="joinFormRef" label-width="100px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="joinForm.name" placeholder="请输入您的真实姓名"></el-input>
          </el-form-item>

          <el-form-item label="学院" prop="college">
            <el-input v-model="joinForm.college" placeholder="请输入您所在的学院"></el-input>
          </el-form-item>

          <el-form-item label="班级" prop="className">
            <el-input v-model="joinForm.className" placeholder="请输入您所在的班级"></el-input>
          </el-form-item>

          <el-form-item label="学号" prop="studentId">
            <el-input v-model="joinForm.studentId" placeholder="请输入您的学号"></el-input>
          </el-form-item>

          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="joinForm.gender">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
              <el-radio label="其他">其他</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="兴趣爱好" prop="hobbies">
            <el-input
              type="textarea"
              v-model="joinForm.hobbies"
              placeholder="请填写您的兴趣爱好"
              :rows="2"
            ></el-input>
          </el-form-item>

          <el-form-item label="申请理由" prop="reason">
            <el-input
              type="textarea"
              v-model="joinForm.reason"
              placeholder="请填写您加入社团的原因"
              :rows="4"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showJoinDialog = false">取消</el-button>
            <el-button type="primary" @click="submitJoinApplication" :loading="submitting">提交申请</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 活动报名表单弹窗 -->
      <el-dialog
        title="活动报名"
        v-model="showRegisterDialog"
        width="40%"
      >
        <div v-if="selectedActivity" class="register-activity-info">
          <h3>{{ selectedActivity.activename }}</h3>
          <p><i class="el-icon-time"></i> {{ formatDateTime(new Date(selectedActivity.activetime)) }}</p>
          <p><i class="el-icon-location"></i> {{ selectedActivity.activeadd }}</p>
        </div>

        <el-form :model="registerForm" :rules="registerFormRules" ref="registerFormRef" label-width="100px">
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="registerForm.realName" placeholder="请输入您的真实姓名"></el-input>
          </el-form-item>

          <el-form-item label="学号" prop="studentId">
            <el-input v-model="registerForm.studentId" placeholder="请输入您的学号"></el-input>
          </el-form-item>

          <el-form-item label="联系方式" prop="contact">
            <el-input v-model="registerForm.contact" placeholder="请输入您的联系方式"></el-input>
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              v-model="registerForm.remark"
              placeholder="如有特殊需求，请在此说明"
              :rows="3"
            ></el-input>
          </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showRegisterDialog = false">取消</el-button>
            <el-button type="primary" @click="submitRegistration" :loading="submittingRegistration">提交报名</el-button>
          </span>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from '../stores/userStore'
import TopBar from '../components/TopBar.vue'
import PostDetailModal from '../components/PostDetailModal.vue'
import PostWaterfall from '../components/PostWaterfall.vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
// 获取用户存储库和路由器
const userStore = useStore()
const router = useRouter()
// 默认图片
const defaultImg = '/src/assets/shehui.png'
// 获取路由参数
const route = useRoute()
const clubId = route.params.id
// 选项卡状态
const tabs = [
  { key: 'posts', label: '社团帖子' },
  { key: 'activities', label: '活动安排' },
  { key: 'members', label: '成员列表' }
]
const activeTab = ref('posts')
// 帖子详情弹窗状态
const selectedPost = ref(null)
// 成员筛选状态
const memberFilter = ref('all')
// 瀑布流组件引用
const postWaterfall = ref(null)
// 加入社团相关状态
const showJoinDialog = ref(false)
const joinFormRef = ref(null)
const submitting = ref(false)
const joinForm = ref({
  name: '',
  college: '',
  className: '',
  studentId: '',
  gender: '男',
  hobbies: '',
  reason: '',
  applyTime: ''
})

// 表单验证规则
const joinFormRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  college: [
    { required: true, message: '请输入所在学院', trigger: 'blur' }
  ],
  className: [
    { required: true, message: '请输入班级', trigger: 'blur' }
  ],
  studentId: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    // { pattern: /^\d{8,12}$/, message: '学号格式不正确', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请填写申请理由', trigger: 'blur' },
    { min: 10, max: 500, message: '理由应该在10-500字之间', trigger: 'blur' }
  ]
}

// 模拟数据 - 实际应用中应该从API获取
const clubData = ref({
  id: 1,
  clubname: '',
  clubimg: '',
  description: '',
  memberCount: 0,
  posts: [],
  active: [],
  members: [],
  admin: []
})

// 从API获取社团数据
const fetchClubData = async (id) => {
  try {
    const response = await axios.get(`http://localhost:5000/clubs/${id}`);
    if (response.data) {
      // 更新社团基本信息
      clubData.value = {
        ...clubData.value,
        ...response.data,
        id: id, // 保存ID
        clubid: response.data.clubid || id, // 保存clubid，如果没有则使用id
        clubimg: response.data.clubimg ? `http://localhost:5000/uploads/${response.data.clubimg}` : defaultImg
      };
      // 获取社团活动
      fetchClubActivities(id);
      // 获取社团帖子
      fetchClubPosts(id);
      // 获取社团成员信息
      fetchClubMembers(id);
    }
  } catch (error) {
    console.error('获取社团数据失败:', error);
    if (error.response) {
      console.error('错误响应数据:', error.response.data);
    }
  }
};

// 获取社团活动
const fetchClubActivities = async (id) => {
  try {
    const response = await axios.get(`http://localhost:5000/clubs/${id}/activities`);
    if (response.data && Array.isArray(response.data)) {
      // 处理活动数据，确保participants字段存在且格式正确
      clubData.value.active = response.data.map(activity => {
        // 确保participants是数组
        if (!activity.participants) {
          activity.participants = [];
        }
        // 记录当前用户是否已报名
        if (Array.isArray(activity.participants) && userStore.user._value && userStore.user._value._id) {
          const isRegistered = activity.participants.some(p =>
            p.userId === userStore.user._value._id ||
            (p.user && (p.user === userStore.user._value._id || p.user._id === userStore.user._value._id))
          );
          if (isRegistered) {
            console.log(`用户已报名活动: ${activity.activename}`);
          }
        }
        return activity;
      });
      console.log('活动数据处理完成');
    } else {
      console.log('未获取到有效的活动数据');
      clubData.value.active = [];
    }
  } catch (error) {
    console.error('获取社团活动失败:', error);
    if (error.response) {
      console.error('错误响应:', error.response.status, error.response.data);
    }
  }
};

// 获取社团帖子
const fetchClubPosts = async (id) => {
  try {
    const response = await axios.get(`http://localhost:5000/clubs/${id}/posts`);
    if (response.data && Array.isArray(response.data)) {
      // 格式化帖子数据以适应组件要求
      clubData.value.posts = response.data.map(post => ({
        ...post,
        _id: post._id || post.id,
        id: post._id || post.id,
        author: post.author || '匿名用户',
        authorimg: post.authorimg || '/src/components/icons/touxiang.png',
        likes: post.likes || 0
      }));
    }
  } catch (error) {
    console.error('获取社团帖子失败:', error);
  }
};

// 获取社团成员信息
const fetchClubMembers = async (id) => {
  try {
    const response = await axios.get(`http://localhost:5000/clubs/${id}/members`);
    if (response.data && Array.isArray(response.data)) {
      clubData.value.members = response.data;
      clubData.value.memberCount = response.data.length;
      console.log('社团成员数据已获取:', clubData.value.members);
      // 在成员数据更新后，打印 isMember 的值
      console.log('[fetchClubMembers] isMember computed value:', isMember.value);
    }
  } catch (error) {
    console.error('获取社团成员失败:', error);
  }
};
// 计算排序后的活动
const sortedActivities = computed(() => {
  return clubData.value.active?.sort((a, b) => new Date(a.activetime) - new Date(b.activetime)) || [];
});
// 过滤后的成员列表
const filteredMembers = computed(() => {
  if (!clubData.value.members) return [];
  if (memberFilter.value === 'all') {
    return clubData.value.members;
  } else if (memberFilter.value === 'admin') {
    return clubData.value.members.filter(m => m.isAdmin);
  }
  return [];
});
// 打开帖子详情
function openPostDetail(post) {
  selectedPost.value = post;
}

// 根据用户id判断当前用户是否是该社团管理员
const isClubAdmin = computed(() => {
  // 检查用户是否已登录
  console.log(userStore.user._value.roles,"juese")
  console.log(userStore.user._value._id,"user")
  console.log("管理员",clubData.value.admin)
  // 方法1: 检查用户ID是否在社团管理员列表中
  if (clubData.value.admin && Array.isArray(clubData.value.admin)) {
    // 如果管理员字段是数组，检查用户ID是否在数组中
    if (clubData.value.admin.includes(userStore.user._value._id)) {
      console.log("用户是社团管理员")
      return true
    }
  } else if (clubData.value.admin) {
    // 如果管理员字段不是数组而是单个值，直接比较
    if (clubData.value.admin === userStore.user._value._id) {
      console.log("用户是社团管理员")
      return true
    }
  }
  console.log("用户不是社团管理员")
  return false
})
// 检查当前用户是否已是社团成员
const isMember = computed(() => {
  const memberid = clubData.value.members.map(member => member.id)
  if (memberid.includes(userStore.user._value._id)) {
      return true
    }
  return false
})
// 转到社团管理页面
const goToClubManage = () => {
  // 使用实际社团的ID跳转到管理页面
  router.push(`/club/${clubId}/manage`)
}

// 修改onMounted以初始化PostWaterfall
onMounted(() => {
  // 加载社团数据
  fetchClubData(clubId);
  // 在数据加载后初始化瀑布流
  nextTick(() => {
    setTimeout(() => {
      if (postWaterfall.value) {
        postWaterfall.value.calculateColumns();
        postWaterfall.value.resizeAllWaterfallItems();
      }
    }, 300);
  });
});

// 打开加入社团对话框
const openJoinDialog = () => {
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.warning('请先登录后再申请加入社团')
    router.push('/login')
    return
  }
  // 如果用户已是成员，提示无需再申请
  if (isMember.value) {
    ElMessage.info('您已经是社团成员了')
    return
  }
  // 如果用户已有待处理的申请，提示等待审核
  if (hasPendingApplication.value) {
    ElMessage.info('您已提交过申请，请等待审核')
    return
  }
  // 预填充用户信息
  joinForm.value.name = userStore.user._value.username || ''
  showJoinDialog.value = true
}

// 检查当前用户是否有待处理的申请
const hasPendingApplication = computed(() => {
  if (!userStore.user._value.loggedIn || !clubData.value.joinApplications) return false
  return clubData.value.joinApplications.some(
    app => app.userId === userStore.user._value._id && app.status === 'pending'
  )
})

// 提交加入申请
const submitJoinApplication = () => {
  joinFormRef.value.validate(async (valid) => {
    if (!valid) return
    submitting.value = true
    try {
      // 设置申请时间
      joinForm.value.applyTime = new Date().toISOString()
      console.log('表单数据:', joinForm.value)
      // 创建申请对象
      const applicationData = {
        userId: userStore.user._value._id,
        username: userStore.user._value.username,
        name: joinForm.value.name,
        college: joinForm.value.college,
        className: joinForm.value.className,
        studentId: joinForm.value.studentId,
        gender: joinForm.value.gender,
        hobbies: joinForm.value.hobbies,
        reason: joinForm.value.reason,
        applyTime: joinForm.value.applyTime,
        avatar: userStore.user._value.avatar,
        clubId: clubData.value.id, // 社团ID (用于API路径)
        clubid: clubData.value.clubid // 社团clubid (必填字段)
      }
      console.log('发送申请数据:', applicationData)
      // 发送申请到服务器
      const response = await axios.post(`http://localhost:5000/clubs/${clubId}/applications`, applicationData)
      ElMessage.success('申请已提交，请等待社团管理员审核')
      showJoinDialog.value = false
      // 重置表单
      joinForm.value = {
        name: '',
        college: '',
        className: '',
        studentId: '',
        gender: '男',
        hobbies: '',
        reason: '',
        applyTime: ''
      }
    } catch (error) {
      console.error('提交申请失败:', error)
      if (error.response) {
        console.error('错误响应:', error.response.data)
        ElMessage.error(`提交失败: ${error.response.data.message || '未知错误'}`)
      } else {
        ElMessage.error('提交申请失败，请稍后重试')
      }
    } finally {
      submitting.value = false
    }
  })
}

// 活动报名相关状态
const showRegisterDialog = ref(false)
const registerFormRef = ref(null)
const submittingRegistration = ref(false)
const selectedActivity = ref(null)
const registerForm = ref({
  realName: '',
  studentId: '',
  contact: '',
  remark: ''
})

// 表单验证规则
const registerFormRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  studentId: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入联系方式', trigger: 'blur' }
  ],
  remark: [
    { min: 0, max: 500, message: '备注长度应在0-500字之间', trigger: 'blur' }
  ]
}

// 活动状态相关逻辑 (基于 status 字段)
function getActivityStatusClass(activity) {
  switch (activity.status) {
    case 'ongoing': return 'activity-card ongoing'
    case 'completed': return 'activity-card completed'
    case 'upcoming':
    default: return 'activity-card upcoming'
  }
}

function getActivityStatusType(activity) {
  switch (activity.status) {
    case 'ongoing': return 'warning'
    case 'completed': return 'info'
    case 'upcoming':
    default: return 'success' // 'upcoming' 使用 success 强调可报名
  }
}

function getActivityStatusText(activity) {
  switch (activity.status) {
    case 'ongoing': return '进行中'
    case 'completed': return '已结束'
    case 'upcoming':
    default: return '未开始'
  }
}

// 基于status字段的判断
function isActivityOngoing(activity) {
  return activity.status === 'ongoing';
}

function isActivityCompleted(activity) {
  return activity.status === 'completed';
}

// 报名按钮的显示逻辑依赖于活动是否是 'upcoming' 状态
function canRegister(activity) {
  return activity.status === 'upcoming';
}

function hasUserRegistered(activity) {
  if (!userStore.user._value || !userStore.user._value._id) return false;
  // 检查活动是否有participants数组
  if (!activity.participants || !Array.isArray(activity.participants)) return false;
  // 多种方式查找当前用户，增加兼容性
  const isRegistered = activity.participants.some(participant => {
    // 检查所有可能的ID字段
    if (participant.userId === userStore.user._value._id) return true;
    if (participant.user && participant.user._id === userStore.user._value._id) return true;
    if (participant.user && participant.user.toString() === userStore.user._value._id) return true;
    return false;
  });
  console.log('用户是否已报名:', isRegistered);
  return isRegistered;
}

function openRegisterDialog(activity) {
  // 检查是否登录
  if (!userStore.user._value || !userStore.user._value._id) {
    ElMessage.warning('请先登录后再报名');
    router.push('/login');
    return;
  }
  // 检查是否为社团成员
  if (!isMember.value) {
    ElMessage.warning('您还不是该社团成员，快去申请加入吧');
    return; // 阻止打开报名对话框
  }
  selectedActivity.value = activity;
  // 预填充用户信息
  registerForm.value = {
    realName: userStore.user._value.username || '',
    studentId: '',
    contact: '',
    remark: ''
  };
  showRegisterDialog.value = true;
}

function submitRegistration() {
  registerFormRef.value.validate(async (valid) => {
    if (!valid) return;
    submittingRegistration.value = true;
    try {
      // 创建报名对象
      const registrationData = {
        userId: userStore.user._value._id,
        username: userStore.user._value.username,
        realName: registerForm.value.realName,
        studentId: registerForm.value.studentId,
        contact: registerForm.value.contact,
        remark: registerForm.value.remark,
        avatar: userStore.user._value.avatar,
        status: 'approved', // 直接设置为已批准状态，无需审核
        registerTime: new Date().toISOString() // 报名时间
      };
      console.log('发送报名数据:', registrationData);
      // 发送报名到服务器
      const activityId = selectedActivity.value._id || selectedActivity.value.id;
      const response = await axios.post(
        `http://localhost:5000/clubs/${clubId}/activities/${activityId}/participants`,
        registrationData
      );
      ElMessage.success('报名成功！您已成功报名参加活动');
      showRegisterDialog.value = false;
      // 重新获取社团活动，更新报名状态
      fetchClubActivities(clubId);
      // 重置表单
      registerForm.value = {
        realName: '',
        studentId: '',
        contact: '',
        remark: ''
      };

    } catch (error) {
      console.error('提交报名失败:', error);
      if (error.response) {
        console.error('错误响应:', error.response.data);
        ElMessage.error(`提交失败: ${error.response.data.message || '未知错误'}`);
      } else {
        ElMessage.error('提交报名失败，请稍后重试');
      }
    } finally {
      submittingRegistration.value = false;
    }
  });
}

async function cancelRegistration(activity) {
  try {
    // 确认取消
    await ElMessageBox.confirm(
      '确定要取消报名吗？此操作不可撤销。',
      '取消报名',
      {
        confirmButtonText: '确定',
        cancelButtonText: '返回',
        type: 'warning'
      }
    );
    // 获取用户ID和活动ID
    let userId = userStore.user._value._id;
    const activityId = activity._id || activity.id;
    if (!userId || !activityId) {
      throw new Error('缺少用户ID或活动ID');
    }

    // 查找确切匹配的参与者记录
    if (activity.participants && Array.isArray(activity.participants)) {
      // 打印每个参与者的详细信息，用于调试
      activity.participants.forEach((p, index) => {
        console.log(`参与者${index}:`, p);
        console.log(`- userId:`, p.userId, typeof p.userId);
        if (p.user) console.log(`- user:`, p.user, typeof p.user);
      });
      // 在MongoDB中，ID可能是字符串或对象，确保我们使用字符串格式进行比较
      if (typeof userId === 'object' && userId._id) {
        userId = userId._id.toString();
      } else if (userId) {
        userId = userId.toString();
      }
    }

    // 调用API删除报名记录
    console.log(`发送删除请求: /clubs/${clubId}/activities/${activityId}/participants/${userId}`);
    const response = await axios.delete(
      `http://localhost:5000/clubs/${clubId}/activities/${activityId}/participants/${userId}`
    );
    ElMessage.success('已取消报名');
    // 重新获取社团活动，更新报名状态
    fetchClubActivities(clubId);
  } catch (error) {
    if (error === 'cancel') return;
    console.error('取消报名失败:', error);
    // 提供更具体的错误信息
    if (error.response) {
      console.error('错误响应状态:', error.response.status);
      console.error('错误响应数据:', error.response.data);
      if (error.response.status === 404) {
        if (error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message);
        } else {
          ElMessage.error('未找到报名记录，请联系管理员');
        }
      } else {
        ElMessage.error(error.response.data?.message || '取消报名失败，请稍后重试');
      }
    } else {
      ElMessage.error('网络错误，请检查网络连接');
    }
  }
}

function formatDateTime(date) {
  if (!date || isNaN(date.getTime())) return '无效日期';
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

function truncateText(text, maxLength) {
  if (!text) return '';
  if (text.length <= maxLength) return text;
  return text.slice(0, maxLength) + '...';
}
</script>
<style>
body {
  background-color: #1f1b24;
  margin: 0;
  padding: 0;
}
</style>
<style scoped>
::-webkit-scrollbar{
  display: none;
}
::-webkit-sticky{
  display: block;
}
.content {
  position: absolute; /* 绝对定位 */
  top: 60px; /* 距离顶部的距离等于顶部区域的高度 */
  left: 10vw; /* 距离左侧的距离等于左侧区域的宽度 */
  right: 10vw;
  bottom: 0; /* 距离底部为0，撑满剩余空间 */
  padding: 20px; /* 为内容添加内边距 */
}

/* 社团头部信息 */
.club-header {
  display: flex;
  padding: 20px;
  background-color: #28232e;
  border-radius: 15px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.img-details {
  margin-right: 30px;
}

.clubimg-details {
  width: 200px;
  height: 200px;
  border: 3px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
}

.club-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.clubname-details {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #fff;
}

.club-description {
  color: #b0bec5;
  line-height: 1.6;
  margin-bottom: 20px;
  max-height: 80px;
  overflow: hidden;
}

.club-stats {
  display: flex;
  margin-bottom: 25px;
}

.stat-item {
  margin-right: 30px;
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #00aeff;
  display: block;
}

.stat-label {
  color: #b0bec5;
  font-size: 14px;
}

.club-actions {
  margin-top: auto;
}

.round-img {
  border-radius: 50%;
  object-fit: cover;
}

/* 导航栏 */
.club-nav {
  display: flex;
  background-color: #28232e;
  border-radius: 15px;
  margin-bottom: 20px;
  overflow: hidden;
}

.nav-item {
  padding: 15px 25px;
  color: #b0bec5;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
}

.nav-item:hover {
  background-color: rgba(0, 174, 255, 0.1);
  color: #fff;
}

.nav-item.active {
  background-color: rgba(0, 174, 255, 0.2);
  color: #00aeff;
  border-bottom: 3px solid #00aeff;
}

/* 内容区域通用样式 */
.section-title {
  color: #fff;
  font-size: 22px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.no-data {
  padding: 40px;
  text-align: center;
  color: #666;
  background-color: #1f1b24;
  border-radius: 10px;
  margin-bottom: 20px;
}

/* 活动区域 */
.club-activities,
.club-members,
.club-posts {
  background-color: #28232e;
  border-radius: 15px;
  padding: 20px;
  margin-bottom: 20px;
}

.activities-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.activity-card {
  background: linear-gradient(135deg, #2c3e50, #3498db);
  color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border: none;
  position: relative;
  overflow: hidden;
  transition: transform 0.3s ease;
}

.activity-card:hover {
  transform: translateY(-5px);
}

.activity-card.upcoming {
  background: linear-gradient(135deg, #2c3e50, #3498db);
}

.activity-card.ongoing {
  background: linear-gradient(135deg, #27ae60, #2ecc71);
}

.activity-card.completed {
  background: linear-gradient(135deg, #7f8c8d, #95a5a6);
  opacity: 0.85;
}

.activity-status {
  position: absolute;
  top: 10px;
  right: 10px;
}

.activity-description {
  margin: 10px 0;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  line-height: 1.5;
}

.register-activity-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #28232e;
  border-radius: 8px;
}

.register-activity-info h3 {
  margin-top: 0;
  color: #409EFF;
  margin-bottom: 10px;
}

/* 成员区域 */
.member-filter {
  margin-bottom: 20px;
}

.members-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.member-card {
  background-color: #1f1b24;
  border-radius: 10px;
  overflow: hidden;
  border: 1px solid rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
}

.member-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  border-color: rgba(0, 174, 255, 0.3);
}

.member-avatar {
  text-align: center;
  padding: 15px 0;
}

.member-avatar img {
  width: 80px;
  height: 80px;
}

.member-info {
  padding: 10px 15px;
  text-align: center;
}

.member-name {
  font-weight: bold;
  font-size: 16px;
  color: #fff;
}

.member-role {
  color: #b0bec5;
  font-size: 13px;
  margin-top: 5px;
}

/* 帖子瀑布流包装器 */
.posts-wrapper {
  width: 100%;
  min-height: 200px;
}

/* 响应式布局 */
@media (max-width: 1400px) {
  .club-header {
    flex-direction: column;
  }

  .img-details {
    margin: 0 auto 20px;
  }
}

@media (max-width: 768px) {
  .activities-grid,
  .members-grid {
    grid-template-columns: 1fr;
  }
}

/* 隐藏滚动条但保留功能 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #1f1b24;
}

::-webkit-scrollbar-thumb {
  background: #444;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.activity-card h4 {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #fff;
}

.activity-info p {
  margin: 8px 0;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
}

.activity-info p i {
  margin-right: 8px;
  font-size: 16px;
}

.activity-action {
  margin-top: 15px;
  text-align: right;
}
</style>
